/*
 * Duplicate Detector Copyright (C) 2010 Marco Biscaro <marcobiscaro2112@gmail.com>
 * 
 * This file is part of Duplicate Detector.
 *
 * Duplicate Detector is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Duplicate Detector is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Duplicate Detector.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.duplicatedetector.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import com.googlecode.duplicatedetector.Constants;
import com.googlecode.duplicatedetector.i18n.Languages;

/**
 * Manages the properties.
 * 
 * @author Marco Biscaro
 */
public final class PropertiesManager implements Constants {

	private static final Properties DEFAULT_PROPERTIES = new Properties();
	private static Properties properties;

	static {
		DEFAULT_PROPERTIES.setProperty("debug", "false");
		DEFAULT_PROPERTIES.setProperty("laf", "System");
		DEFAULT_PROPERTIES.setProperty("language", Languages
				.getDefaultLanguage());
		properties = new Properties(DEFAULT_PROPERTIES);
		if (PROPERTIES_FILE.exists()) {
			InputStream in = null;
			try {
				in = new FileInputStream(PROPERTIES_FILE);
				properties.load(in);
				in.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private PropertiesManager() {
		// can not instantiate
	}

	public static String getProperty(String key) {
		return properties.getProperty(key);
	}

	public static void setProperty(String key, Object value) {
		properties.setProperty(key, value.toString());
	}

	public static synchronized void write() {
		OutputStream out = null;
		try {
			out = new FileOutputStream(PROPERTIES_FILE);
			properties.store(out, "Duplicate Detector properties");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (IOException e) {
					// simple ignore
				}
			}
		}
	}

}
